<script setup>
import { useRouter } from 'vue-router';
import { onMounted } from 'vue'
import { userStore } from '@/store/index.js'
import axios  from 'axios'

const router = useRouter();



const userItemStore = userStore()

const goLogin = ()=>{
  router.push("/login").catch(err => err);
}
//跳转到首页
const  goHome=()=> {
  router.push("/").catch(err => err);
}

//判断是否登录
const isLogged = ()=>{
  axios.get("/user/isLogged").then(resp=>{
    const user = resp.data;
    userItemStore.updateUser(user);
    userItemStore.updateLoginStatus(true)
  }).catch(error => {
    console.log(`用户未登录 ${error}`);
  });
}

//推出
const logout = ()=>{
  axios.get('/user/logout').then(resp=>{
    //删除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    //提示信息
    userItemStore.updateUser(null);
    userItemStore.updateLoginStatus(false);
    //跳转到主页
    goHome();
  })
}
const goRegister = ()=>{
  router.push("/register").catch(err=>err);
}

onMounted(()=>{
  isLogged();
})
const goCart = ()=>{
  router.push("/cart").catch(err=>err)
}
</script>

<template>
  <!-- 顶部 -->
  <div>
    <el-row class="banner">
      <!-- 左边的logo -->
      <el-col :span="7">
        <img src="../assets/logo.png" alt="蜗牛书城">
      </el-col>
      <!--  搜索文本框和按钮 -->
      <el-col :span="7">
        <el-input size="small"
                  placeholder="搜索关键字"
                  clearable style="width: 250px;"></el-input>
        <el-button size="small" type="primary"
                   icon="el-icon-search">搜索</el-button>
      </el-col>
      <el-col :span="10" style="text-align: right">
        <!--  后面的按钮 -->
        <el-button-group>
          <!-- 显示以后才显示以下按钮 -->
          <template v-if="userItemStore.loggedIn">

            <el-button type="plain"
                       size="small">
              欢迎您：{{userItemStore.user.account}}</el-button>
            <el-button type="primary" size="small" @click="goCart">购物车</el-button>
            <el-button type="primary" size="small" >我的收藏</el-button>
            <el-button type="primary" size="small" >我的订单</el-button>
            <el-button type="primary"
                       size="small" @click="logout">退出</el-button>
          </template>
          <template v-else>
            <el-button type="primary" size="small"
                       @click="goLogin">登录</el-button>
            <el-button type="primary" size="small"  @click="goRegister">注册</el-button>
          </template>
          <!-- 无论是否登录都显示-->
          <el-button type="primary" size="small"
                     @click="goHome">首页</el-button>
        </el-button-group>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>

</script>

<style scoped>
.banner {
  display: flex;
  justify-content: center;
  /* 底部对齐 */
  align-items: flex-end;
  padding: 5px;
  top: 0;
  left: 0;
  width: 100%;
  /* 左上角到右下角 */
  background: linear-gradient(to bottom right, #a9dff4, #688df4, #eef2ce);
}
</style>